package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.io.unit.DataUnit;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.util.StringUtil;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.DeviceDataByDayDto;
import com.zzyl.nursing.dto.QueryDevicePropertyStatusRequestDto;
import com.zzyl.nursing.dto.UserAddRequestDto;
import com.zzyl.nursing.dto.UserLoginRequestDto;

import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.mapper.FamilyMemberElderMapper;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

//import static sun.awt.geom.Curve.round;

/**
 * 老人家属Service业务层处理
 * 
 * @author alexis
 * @date 2025-01-09
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService
{
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private WechatService wechatService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ElderServiceImpl elderService;

    @Autowired
    private FamilyMemberElderMapper familyMemberElderMapper;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    /**
     * 查询老人家属
     * 
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id)
    {
        return familyMemberMapper.selectById(id);
    }

    /**
     * 查询老人家属列表
     * 
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember)
    {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember)
    {
        return familyMemberMapper.insert(familyMember);
    }

    /**
     * 修改老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember)
    {
        return familyMemberMapper.updateById(familyMember);
    }

    /**
     * 批量删除老人家属
     * 
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids)
    {
        return familyMemberMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除老人家属信息
     * 
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id)
    {
        return familyMemberMapper.deleteById(id);
    }

    /**
     * 小程序登录方法
     *
     * @param userLoginRequestDto 请求数据
     * @return 登录结果，包含token和nickname
     */
    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        // 1.调用微信官方接口获取openId
        String openId = wechatService.getOpenId(userLoginRequestDto.getCode());

        // 2.根据openId查询数据库获取用户信息
        FamilyMember familyMember = getOne(Wrappers.<FamilyMember>lambdaQuery().eq(FamilyMember::getOpenId, openId));

        // 3.如果用户信息不存在，就创建一个用户，并绑定openId
        if (ObjectUtils.isEmpty(familyMember)) {
            // 新用户
            familyMember = new FamilyMember();
            familyMember.setOpenId(openId);
        }

        // 4.调用微信接口获取手机号
        String phoneNumber = wechatService.getPhoneNumber(userLoginRequestDto.getPhoneCode());
        // 不论是新用户还是老用户，都更新手机号
        familyMember.setPhone(phoneNumber);

        // 5.保存或更新用户，如果是新增，要生成一个用户名
        saveOrUpdateFamilyMember(familyMember);

        // 6.封装用户信息到token中，返回给小程序
        LoginVo loginVo = new LoginVo();
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", familyMember.getId());
        claims.put("nickName", familyMember.getName());

        String token = tokenService.createToken(claims);
        loginVo.setToken(token);
        loginVo.setNickName(familyMember.getName());

        // 返回结果
        return loginVo;
    }

    /**
     * 新增或更新老人家属
     * @param familyMember  老人家属对象
     */
    private void saveOrUpdateFamilyMember(FamilyMember familyMember) {
        // 判断id是否为空
        if (ObjectUtils.isEmpty(familyMember.getId())) {
            // 新增
            // 生成一个随机的用户名，规则是：一个随机的好听的名字+手机号后4位
            String prefix = DEFAULT_NICKNAME_PREFIX.get((int) (Math.random() * DEFAULT_NICKNAME_PREFIX.size()));
            String nickName = prefix + familyMember.getPhone().substring(7);
            familyMember.setName(nickName);
            familyMemberMapper.insert(familyMember);
        } else {
            // 更新
            familyMemberMapper.updateById(familyMember);
        }
    }

    /**
     * 绑定家人
     *
     * @param userAddRequestDto 请求数据
     */
    @Override
    public void add(UserAddRequestDto userAddRequestDto) {
        // 1.获取当前登录用户id
        Long userId = UserThreadLocal.getUserId();

        // 2.根据身份证号判断老人是否存在
        Elder elder = elderService.getOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getIdCardNo, userAddRequestDto.getIdCard()));
        if (ObjectUtils.isEmpty(elder)){
            throw new BaseException("老人不存在");
        }

        // 3.老人存在，绑定老人
        FamilyMemberElder familyMemberElder = new FamilyMemberElder();
        familyMemberElder.setElderId(elder.getId());
        familyMemberElder.setFamilyMemberId(userId);
        familyMemberElder.setRemark(userAddRequestDto.getRemark());
        familyMemberElderMapper.insert(familyMemberElder);
    }

    /**
     * 查询家人列表
     *
     * @return 家人列表
     */
    @Override
    public List<FamilyMemberElderVo> selectMyElderList() {
        Long userId = UserThreadLocal.getUserId();
        List<FamilyMemberElder> familyMemberElders = familyMemberElderMapper.selectList(Wrappers.<FamilyMemberElder>lambdaQuery().eq(FamilyMemberElder::getFamilyMemberId, userId));
        List<FamilyMemberElderVo> familyMemberElderVos = BeanUtil.copyToList(familyMemberElders, FamilyMemberElderVo.class);
        familyMemberElderVos.forEach(item -> {
            item.setElderName(elderService.getById(item.getElderId()).getName());
        });
        return familyMemberElderVos;
    }

    /**
     * 分页查询已绑定家人列表
     *
     * @param pageNum  页码
     * @param pageSize 页大小
     * @return 家人列表
     */
    @Override
    public List<FamilyMemberElderBedVo> selectMyElderListByPage(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);

        return familyMemberMapper.selectMyElderListAll(UserThreadLocal.getUserId());
    }

    /**
     * 查询健康数据
     *
     * @param queryDevicePropertyStatusRequestDto 请求数据
     * @return 返回结果
     */
    @Override
    public PropertyStatusInfoVo queryDevicePropertyStatus(QueryDevicePropertyStatusRequestDto queryDevicePropertyStatusRequestDto) {
        // 获取设备信息
        Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, queryDevicePropertyStatusRequestDto.getDeviceName()));
        // 从redis获取设备最新数据
        List<DeviceData> deviceData = (List<DeviceData>) redisTemplate.opsForHash().get(CacheConstants.IOT_DEVICE_DATA_LATEST, device.getIotId());
        // 封装数据
        PropertyStatusInfoVo propertyStatusInfoVos = new PropertyStatusInfoVo();
        Map<String, List<ProperStatusInfo>> listMap = new HashMap<>();
        List<ProperStatusInfo> properStatusInfos = new ArrayList<>();
        ProperStatusInfo properStatusInfo = new ProperStatusInfo();
        deviceData.forEach(item -> {
            properStatusInfo.setDataType("int");
            properStatusInfo.setIdentifier("HearRate");
            properStatusInfo.setName("心率");
            properStatusInfo.setTime(String.valueOf(item.getAlarmTime().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()));
            properStatusInfo.setUnit("");
            properStatusInfo.setValue(item.getDataValue());
            properStatusInfos.add(properStatusInfo);
        });
        listMap.put("propertyStatusInfo", properStatusInfos);
        propertyStatusInfoVos.setList(listMap);

        return propertyStatusInfoVos;
    }

    /**
     * 按天统计查询指标数据
     *
     * @param deviceDataByDayDto 请求参数
     * @return 返回结果
     */
    @Override
    public List<DeviceDataByDayVo> queryDeviceDataListByDay(DeviceDataByDayDto deviceDataByDayDto) {
        // 将开始时间戳转换成LocalDataTime
        Instant startInstant = Instant.ofEpochMilli(deviceDataByDayDto.getStartTime());
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime startLocalDateTime = startInstant.atZone(zoneId).toLocalDateTime();

        // 将结束时间戳转换为LocalDataTime
        Instant endInstant = Instant.ofEpochMilli(deviceDataByDayDto.getEndTime());
        LocalDateTime endLocalDateTime = endInstant.atZone(zoneId).toLocalDateTime();

        String iotId = deviceDataByDayDto.getIotId();
        String functionId = deviceDataByDayDto.getFunctionId();

        List<DeviceDataByDayVo> deviceDataByDayVos = new ArrayList<>();

        for (int i = 0 ; i<= 23; i++){
            int sum = 0;
            DeviceDataByDayVo deviceDataByDayVo = new DeviceDataByDayVo();
            LocalDateTime sLocalDateTime = startLocalDateTime.plusHours(i);
            endLocalDateTime = startLocalDateTime.plusHours(i+1);
            List<DeviceData> deviceDataList = deviceDataMapper.selectList(Wrappers.<DeviceData>lambdaQuery()
                    .eq(DeviceData::getIotId, iotId)
                    .eq(DeviceData::getFunctionId, functionId)
                    .between(DeviceData::getAlarmTime, sLocalDateTime, endLocalDateTime));
            for (DeviceData deviceData : deviceDataList) {
                sum += Integer.valueOf(deviceData.getDataValue());
//                sum = Integer.parseInt(sum + deviceData.getDataValue());
            }
//            for (int i1 = 0; i1 < deviceDataList.size(); i1++) {
//                avg = avg + Double.parseDouble(deviceDataList.get(i1).getDataValue());
//            }
            try {
                sum /= deviceDataList.size();
            } catch (Exception e) {
                sum =  0;
            }
//            Double avg = (double) Math.round(sum / deviceDataList.size());
            deviceDataByDayVo.setDateTime(sLocalDateTime.toLocalTime().format(DateTimeFormatter.ofPattern("HH:mm")));
            deviceDataByDayVo.setDataValue(sum);
            deviceDataByDayVos.add(deviceDataByDayVo);

        }
        return deviceDataByDayVos;
    }

    /**
     * 按周统计查询指标数据
     *
     * @param deviceDataByDayDto 请求参数
     * @return 返回结果
     */
    @Override
    public List<DeviceDataByDayVo> queryDeviceDataListByWeek(DeviceDataByDayDto deviceDataByDayDto) {
        // 将开始时间戳转换成LocalDataTime
        Instant startInstant = Instant.ofEpochMilli(deviceDataByDayDto.getStartTime());
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime startLocalDateTime = startInstant.atZone(zoneId).toLocalDateTime();

        // 将结束时间戳转换为LocalDataTime
        Instant endInstant = Instant.ofEpochMilli(deviceDataByDayDto.getEndTime());
        LocalDateTime endLocalDateTime = endInstant.atZone(zoneId).toLocalDateTime();

        String iotId = deviceDataByDayDto.getIotId();
        String functionId = deviceDataByDayDto.getFunctionId();

        List<DeviceDataByDayVo> deviceDataByDayVos = new ArrayList<>();

        for (int i = 0 ; i< 7; i++){
            int sum = 0;
            DeviceDataByDayVo deviceDataByDayVo = new DeviceDataByDayVo();
            LocalDateTime sLocalDateTime = startLocalDateTime.plusDays(i);
            endLocalDateTime = startLocalDateTime.plusDays(i+1);
            List<DeviceData> deviceDataList = deviceDataMapper.selectList(Wrappers.<DeviceData>lambdaQuery()
                    .eq(DeviceData::getIotId, iotId)
                    .eq(DeviceData::getFunctionId, functionId)
                    .between(DeviceData::getAlarmTime, sLocalDateTime, endLocalDateTime));
            for (DeviceData deviceData : deviceDataList) {
                sum += Integer.valueOf(deviceData.getDataValue());

            }

            try {
                sum /= deviceDataList.size();
            } catch (Exception e) {
                sum =  0;
            }
            deviceDataByDayVo.setDateTime(sLocalDateTime.toLocalDate().format(DateTimeFormatter.ofPattern("MM:dd")));
            deviceDataByDayVo.setDataValue(sum);
            deviceDataByDayVos.add(deviceDataByDayVo);

        }
        return deviceDataByDayVos;
    }
}














